import React, { useState } from 'react';
import { Card, Upload, Button, Progress, Alert, message } from 'antd';
import { UploadOutlined, FileImageOutlined, VideoCameraOutlined } from '@ant-design/icons';

const { Dragger } = Upload;

// 分片上传配置
const CHUNK_SIZE = 2 * 1024 * 1024; // 2MB 分片大小
const MAX_FILE_SIZE = 500 * 1024 * 1024; // 500MB 最大文件大小

export default function UploadTest() {
    const [uploadProgress, setUploadProgress] = useState({});
    const [uploading, setUploading] = useState(false);

    // 生成文件唯一标识
    const generateFileId = (file) => {
        return `${file.name}-${file.size}-${file.lastModified}`;
    };

    // 分片上传文件
    const uploadFileInChunks = async (file) => {
        const fileId = generateFileId(file);
        const chunks = Math.ceil(file.size / CHUNK_SIZE);
        
        setUploadProgress(prev => ({
            ...prev,
            [fileId]: { current: 0, total: chunks, percentage: 0 }
        }));

        try {
            // 1. 初始化上传
            const token = localStorage.getItem('token');
            const initResponse = await fetch('http://localhost:3001/api/upload/init', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                },
                body: JSON.stringify({
                    fileName: file.name,
                    fileSize: file.size,
                    fileType: file.type,
                    chunks: chunks
                })
            });

            if (!initResponse.ok) {
                throw new Error('初始化上传失败');
            }

            const initResult = await initResponse.json();
            if (!initResult.success) {
                throw new Error(initResult.message || '初始化上传失败');
            }

            // 2. 上传分片
            for (let chunkIndex = 0; chunkIndex < chunks; chunkIndex++) {
                const start = chunkIndex * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);

                const formData = new FormData();
                formData.append('chunk', chunk);
                formData.append('chunkIndex', chunkIndex);
                formData.append('fileId', fileId);
                formData.append('fileName', file.name);

                const chunkResponse = await fetch('http://localhost:3001/api/upload/chunk', {
                    method: 'POST',
                    headers: {
                        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                    },
                    body: formData
                });

                if (!chunkResponse.ok) {
                    throw new Error(`分片 ${chunkIndex + 1} 上传失败`);
                }

                const chunkResult = await chunkResponse.json();
                if (!chunkResult.success) {
                    throw new Error(chunkResult.message || `分片 ${chunkIndex + 1} 上传失败`);
                }
                
                // 更新进度
                const percentage = Math.round(((chunkIndex + 1) / chunks) * 100);
                setUploadProgress(prev => ({
                    ...prev,
                    [fileId]: { 
                        current: chunkIndex + 1, 
                        total: chunks, 
                        percentage 
                    }
                }));
            }

            // 3. 完成上传
            const completeResponse = await fetch('http://localhost:3001/api/upload/complete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                },
                body: JSON.stringify({
                    fileId: fileId,
                    fileName: file.name
                })
            });

            if (!completeResponse.ok) {
                throw new Error('完成上传失败');
            }

            const completeResult = await completeResponse.json();
            if (!completeResult.success) {
                throw new Error(completeResult.message || '完成上传失败');
            }

            message.success(`${file.name} 上传成功`);
            return completeResult.data;

        } catch (error) {
            console.error('分片上传错误:', error);
            message.error(`${file.name} 上传失败: ${error.message}`);
            throw error;
        } finally {
            // 清理进度状态
            setUploadProgress(prev => {
                const newState = { ...prev };
                delete newState[fileId];
                return newState;
            });
        }
    };

    // 处理文件上传
    const handleFileUpload = async (file) => {
        if (file.size > MAX_FILE_SIZE) {
            message.error(`文件大小不能超过 ${MAX_FILE_SIZE / 1024 / 1024}MB`);
            return false;
        }

        setUploading(true);

        try {
            await uploadFileInChunks(file);
        } catch (error) {
            console.error('上传错误:', error);
        } finally {
            setUploading(false);
        }

        return false; // 阻止默认上传行为
    };

    return (
        <div style={{ padding: '24px' }}>
            <Card title="分片上传测试" style={{ marginBottom: '24px' }}>
                <Alert
                    message="分片上传功能说明"
                    description="此页面用于测试大文件的分片上传功能。支持拖拽上传，自动分片处理大文件。"
                    type="info"
                    showIcon
                    style={{ marginBottom: '16px' }}
                />

                <div style={{ marginBottom: '16px' }}>
                    <h3>视频上传测试</h3>
                    <Dragger
                        beforeUpload={handleFileUpload}
                        showUploadList={false}
                        accept="video/*"
                        multiple={true}
                        disabled={uploading}
                    >
                        <p className="ant-upload-drag-icon">
                            <VideoCameraOutlined />
                        </p>
                        <p className="ant-upload-text">点击或拖拽视频到此区域上传</p>
                        <p className="ant-upload-hint">
                            支持多个视频文件，单个文件最大 500MB
                        </p>
                    </Dragger>
                </div>

                <div style={{ marginBottom: '16px' }}>
                    <h3>图片上传测试</h3>
                    <Dragger
                        beforeUpload={handleFileUpload}
                        showUploadList={false}
                        accept="image/*"
                        multiple={true}
                        disabled={uploading}
                    >
                        <p className="ant-upload-drag-icon">
                            <FileImageOutlined />
                        </p>
                        <p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
                        <p className="ant-upload-hint">
                            支持多个图片文件，单个文件最大 500MB
                        </p>
                    </Dragger>
                </div>

                {/* 上传进度显示 */}
                {Object.keys(uploadProgress).length > 0 && (
                    <div style={{ marginTop: '16px' }}>
                        <h3>上传进度</h3>
                        {Object.entries(uploadProgress).map(([fileId, progress]) => (
                            <div key={fileId} style={{ marginBottom: '8px' }}>
                                <div style={{ marginBottom: '4px' }}>
                                    <span>{fileId}</span>
                                    <span style={{ marginLeft: '8px', color: '#666' }}>
                                        {progress.current}/{progress.total} 分片
                                    </span>
                                </div>
                                <Progress 
                                    percent={progress.percentage} 
                                    status="active"
                                    strokeColor="#1890ff"
                                />
                            </div>
                        ))}
                    </div>
                )}

                {uploading && (
                    <Alert
                        message="正在上传文件..."
                        type="info"
                        showIcon
                        style={{ marginTop: '16px' }}
                    />
                )}
            </Card>
        </div>
    );
} 